import datetime
import requests
from base64 import b64encode
import models
import configparser


config = configparser.ConfigParser()
config.read('config.ini')


def send_data(ids: [str], title: str, content: str, extras: dict = None):
    auth = b64encode('{}:{}'.format(config.get('jpush', 'appKey'), config.get('jpush', 'masterSecret')).encode('utf-8')).decode('utf-8')
    requests.post('https://{}{}'.format(config.get('jpush', 'url'), config.get('jpush', 'path')), headers={
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + auth
    },  json={
        'platform': 'all',
        'audience': {
            'registration_id': ids
        },
        'notification': {
            'alert': content,
            'android': {
                'alert': content,
                'title': title,
                'extras': extras
            },
            'ios': {
                'alert': content,
                'badge': '+1',
                'sound': 'default',
                'extras': extras
            }
        }
    })
    pass


def row2dict(row):
    d = {}
    for col in row.__table__.columns:
        v = getattr(row, col.name)
        if isinstance(v, datetime.datetime):
            d[col.name] = v.strftime('%Y-%m-%d %H:%M:%S')
        else:
            d[col.name] = v
    return d


def push_notify(title: str, content: str, extras: models.Record | models.Card | models.Project, login_user: models.User):
    families = login_user.families.filter(models.Family.state == True)
    if families is None:
        return
    ids = map(lambda family: family.family.pushId, families)
    data = row2dict(extras)
    if isinstance(extras, models.Record):
        data['type'] = 'record'
    elif isinstance(extras, models.Card):
        data['type'] = 'card'
    elif isinstance(extras, models.Project):
        data['type'] = 'project'
    send_data(list(ids), title, content, data)
    pass
